<template>
  <a-spin :spinning="confirmLoading">
    <!-- 主表单区域 -->
    <div>
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-row>
          <a-col :span="8">
             <a-form-model-item label="供应商" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="supplierId">
              <j-search-select-tag v-model="model.supplierId" :async="true" dict="bas_supplier,name,id" :disabled="disabled"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="销售订单号" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="salOrderWrOrderNo">
              <a-input v-model="model.salOrderWrOrderNo" placeholder="请输入" @blur="onCodeNameBlur" :readOnly="disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="状态" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="status">
              <a-input  :value="statusMap[model.status]" placeholder="请输入" :readOnly="disabled" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
             <a-form-model-item label="备注" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入" :readOnly="disabled" />
            </a-form-model-item>
          </a-col>
         
        </a-row>
       
        <!-- 子表单区域 -->
        <a-tabs v-model="activeKey" @change="handleChangeTabs">
          <a-tab-pane tab="明细" :key="refKeys[0]" :forceRender="true">
            <j-vxe-table keep-source :ref="refKeys[0]" :columns="entryTable.columns" :dataSource="entryTable.dataSource"
              :maxHeight="300" :disabled="disabled" :rowNumber="false" :rowSelection="!disabled" :toolbar="!disabled"
              :resizable="true" :edit-config="{ trigger: 'click', mode: 'row', showIcon: false }"
              @edit-actived="({ row }) => setMaterialUnitOptions(row, $refs.entryTable)" @added="onInEntryAdded"
              @valueChange="onEntryValueChange" />
          </a-tab-pane>


        </a-tabs>
        <!-- <bill-footer ref="billFooter" :model="model" :disabled="disabled" :action="action" /> -->
      </a-form-model>
    </div>

  </a-spin>
</template>

<script>

import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { OrderFormMixin, OrderFormGridMixin } from '../../common/mixins/OrderFormMixin'
import { OrderVxeTableMixin } from '../../common/mixins/OrderVxeTableMixin'
// import BillFooter from "../../common/components/BillFooter";
import VxeTableColumnsSetter from "../../common/components/VxeTableColumnsSetter";

export default {
  name: 'productForm',
  mixins: [JVxeTableModelMixin, OrderFormMixin, OrderFormGridMixin, OrderVxeTableMixin],
  components: { VxeTableColumnsSetter },

  data() {
    return {
      model: {//设置初始值的属性、程序赋值的响应式属性
        supplierId: "",
        salOrderWrOrderId: "",
        salOrderWrOrderNo: "",
        attachmentUrl: "",
        remark: "",
        status: "",
      },
       statusMap: { // 状态映射关系
      '1': '生产中',
      '2': '待质检',
      '3': '已完成',
      '4': '质检不合格'
    },
      validatorRules: {},

      entryNoStep: 10,
      addDefaultRowNum: 1,
      refKeys: ['entryTable',],
      tableKeys: ['entryTable',],
      activeKey: 'entryTable',

      // 明细
      entryTable: {
        loading: false,
        dataSource: [],
        url: {
          list: '/wr/supplierProduceTask/queryById'
        },
        columns: [
          {
            title: '产品名称',
            key: 'productId',
            type: JVXETypes.selectSearch,
            options: [],
            dictCode: "bas_product,name,id",
            width: "300px",
            fixed: 'left',
            defaultValue: '',
          },
          {
            title: '单价',
            key: 'amount',
            width: "150px",
            align: "center",
            formatter: this.formatQty,
            placeholder: '请输入',
            defaultValue: '',
            // statistics: ['sum'],
          },
           {
            title:'币种',
            width:150,
            align:"center",
            key: 'currency'
          },
          {
            title: '数量',
            key: 'qty',
            width: "150px",
            align: "center",
            formatter: this.formatQty,
            defaultValue: '',
            // statistics: ['sum'],
          },
          {
            title: '创建者',
            key: 'createBy',
            width: "150px",
            align: "center",
            defaultValue: '',
          },
          {
            title: '创建时间',
            key: 'createTime',
            width: "300px",
            align: "center",
            customRender: t => !t ? "" : (t.length > 10 ? t.substr(0, 10) : t),
            defaultValue: '',
            // statistics: ['sum'],
          },
          
        ]
      },

      url: {

        add: "/base/basProduct/add",
        edit: "/base/basProduct/edit",
        check: "/stock/stkIo/check",
        ebpm: "/stock/stkIo/bpm/end",
        execute: "/stock/stkIo/execute",
        void: "/stock/stkIo/void",
      },

    }
  },

  created() {
    // 等待物料options加载完成
    this.initMaterialRelated();
  },
  methods: {
    onCodeNameBlur(val) {
      console.log('1111');

      if (!this.model.code || this.model.code.length === 0 || !this.model.name || this.model.name.length === 0)
        return;
      if (!this.model.auxName || this.model.auxName.length === 0)
        this.model.auxName = this.model.code + ' ' + this.model.name;
    },
    addBefore() {
      this.entryTable.dataSource = [];
    },

    addAfter() {
      this.$refs.billHeader.fillBillNo(
        'stk_qtrk_bill_no',
        (billNo) => {
          this.$nextTick(() => {
            //异步执行原因，初始空白行增加时，billNo可能还未获得！
            let rows = this.$refs.entryTable.getNewDataWithId();
            for (let row of rows) {
              this.$refs.entryTable.setValues([{ rowKey: row.id, values: { batchNo: billNo + '-' + row.entryNo } }]);
            }
          })
        });
    },

    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    editAfter() {
      setTimeout(() => {
        if (this.model.id) {
          let params = { id: this.model.id };
          this.requestSubTableData(this.entryTable.url.list, params, this.entryTable, () => {
            console.log('明细数据加载结果：', this.entryTable.dataSource); // 新增日志
            // 检查明细数据是否为空
            if (!this.entryTable.dataSource || this.entryTable.dataSource.length === 0) {
              console.warn('明细数据为空，可能接口返回空或参数错误');
            }
          });
        }
      }, 500);

    },

    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        materialList: allValues.tablesValue[0].tableData,
      }
    },

    onEntryValueChange(event) {
      const { type, value, oldValue, row, column, target, isSetValues } = event;
      if (value === oldValue || isSetValues) return;

      switch (column.property) {
        case "entryNo": //联动：分录号 --> 批次
          if (!row.batchNo || row.batchNo === this.model.billNo + "-" + oldValue) {
            target.setValues([{ rowKey: row.id, values: { batchNo: this.model.billNo + "-" + value } }]);
          }
          break;
        case "materialId":
          this.handleMaterialChange(row, target);
          break;
        case "unitId":
          if (!oldValue || oldValue.length === 0 || !value || value.length === 0) break;
          let rate = this.getUnitRate(row.materialId, oldValue, value);
          if (!rate)
            target.setValues([{ rowKey: row.id, values: { unitId: oldValue } }]);
          else
            target.setValues([{
              rowKey: row.id,
              values: {
                qty: (row.qty * rate).toFixed(3),
                price: (row.price / rate).toFixed(2)
              }
            }]);
          break;
        case "qty":
        case "price":
          target.setValues([{
            rowKey: row.id,
            values: { cost: (row.qty * row.price).toFixed(2) }
          }]);
          break;
      }
    },

    costValidator({ cellValue, row, column }, callback, target) {
      const v = Number(cellValue);
      if (isNaN(v)) {
        callback();
        return;
      }

      let diff = v - Number((row.qty * row.price).toFixed(2));
      if (diff < -0.01001 || diff > 0.01001) {
        callback(false, '${title}的输入值与计算值相差超过0.01元！');
      } else {
        callback(true); //true：通过验证
      }
    },

  }
}
</script>

<style lang="less" scoped>
@import "../../common/less/BillForm.less";
</style>
